package com.xing.oss.service.impl;

import com.xing.oss.service.FileService;
import com.xing.oss.utils.ConstantOssPropertiesUtil;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.PutObjectRequest;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.Date;
import java.util.UUID;

/**
 * @author 邢福豪
 * @date 2022/7/27 14:42
 */

@Service
public class FileServiceImpl implements FileService {


    @Override
    public String upload(MultipartFile file) {

        //Endpoint以杭州为例，其它Region请按照实际情况填写
        String endpoint = ConstantOssPropertiesUtil.ENDPOINT;
        String bucketName = ConstantOssPropertiesUtil.BUCKET_NAME;
        String accessKeyId = ConstantOssPropertiesUtil.KEY_ID;
        String accessKeySecret = ConstantOssPropertiesUtil.KEY_SECRET;


        try {

            //创建OSSClient实例
            OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

            //上传文件流
            InputStream inputStream = file.getInputStream();
            String fileName = file.getOriginalFilename();
            //生成随机唯一值，使用uuid,添加到文件名称里面
            String uuid = UUID.randomUUID().toString().replaceAll("-", "");
            fileName = uuid + fileName;

            //按照当前日期，创建文件夹，上传到创建文件夹里面
            //2022/07/27/01.jpg
            String timeUrl = new DateTime().toString("yyyy/MM/dd");
            fileName = timeUrl + "/" + fileName;

            // 上传字符串。
            ossClient.putObject(bucketName, fileName, inputStream);
            ossClient.shutdown();

            //上传后的文件路径
            String url = "https://" + bucketName + "." + endpoint + "/" + fileName;
            return url;

        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}